<?php
namespace App\Process;

use App\Model\Device;
use Hyperf\Config\Annotation\Value;
use Hyperf\Process\AbstractProcess;
use Hyperf\Process\Annotation\Process;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Logger\LoggerFactory;
#[Process(name:'data1-subsribe')]
class Data1SubscribeProcess extends AbstractProcess{

    public function handle(): void
     {
         $connectSettings = (new \PhpMqtt\Client\ConnectionSettings())
             ->setUsername('admin')
             ->setPassword('256055cbacba@189');
         $mqtt = new \PhpMqtt\Client\MqttClient('47.111.230.9', 1883);
         $mqtt->connect($connectSettings,true);
         $mqtt->subscribe('/v1/device/867713070797428/rx', function ($topic, $message, $retained, $matchedWildcards) use($mqtt) {
             $strLen = strlen($message);
             $messageResult = [];
             $messageResultLog = [];
             for ($i = 0; $i < $strLen; $i ++) {
                 $item = ord(substr($message, $i, 1));
                 $messageResult[] = $item;
                 //转为16进制记录日志 方便使用
                 $messageResultLog[] = dechex($item);
             }
             preg_match('/(device\/)(.*)(?)(\/rx)/', $topic, $result);
             $imei = $result[2];
             $device = Device::where('iot_sn', $imei)->first();
             if(!$device){
                 $log_name = 'device' . date('Y-m-d', time());
                 $loggerFactory = container()->get(\Hyperf\Logger\LoggerFactory::class);
                 $logger = $loggerFactory->get($log_name, 'device');
                 $logger->error('device['.$imei.'] not found -----'.date('Y/m/d H:i:s',time()));
             }
             $device->iotEventHandle($messageResult,$mqtt);

         }, 0);
         $mqtt->loop(true);
         $mqtt->disconnect();
      }
}
